package com.kinon.ceshiaccount.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.bean.LoginBean;
import com.kinon.ceshiaccount.bean.UrlBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.network.http.HttpApiUrl;
import com.kinon.ceshiaccount.service.AdImageService;
import com.kinon.ceshiaccount.service.GetMakemealService;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.sunmi.util.SharedPreferencesUtil;
import com.kinon.ceshiaccount.util.AppInfoUtil;
import com.kinon.ceshiaccount.util.LoadDialogManager;
import com.kinon.ceshiaccount.util.MyShowDialog;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.CustomDialog;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.DSKernel;
import sunmi.ds.callback.IConnectionCallback;

import static com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath.WELCOME_IMG_ID;

/**
 * Created by luohao on 2017-06-29.
 * 登录
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener,
        View.OnFocusChangeListener{

    private TextInputLayout til_account;
    private TextInputEditText et_accountNum;
    private TextInputLayout til_pwd;
    private TextInputEditText et_password;
    private Button btn_login;
    private Button btn_urgentLogin;
    private TextView tv_appSersion;
      /**用户登录类型*/
    private final String USER_LOGIN_TYPE="3";

    DSKernel mDSKernel;// SDK核心类
    long taskId;

    private final String [] READ_PHONE_STATE_PERMISSION=new String[]
            {Manifest.permission.READ_PHONE_STATE};
    private String  sunmiSN="";
    private int errorNum=0;

    private String serverUrl="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
//        isPermission();
        isgetUrl();
        initView();
        initSDK();
//        getSN();

    }


    @Override
    protected void onReadPhoneStatePermission() {
        super.onReadPhoneStatePermission();
        CustomDialog dialog=new CustomDialog(getApplicationContext(),
                "是否去设置页面开启权限", new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                if(btn==1){
                    //跳到应用设置页面
                    goToAppSetting();
                }
            }
        });
        dialog.show();
    }
    private void goToAppSetting(){
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    private void initView() {
        Constant.IS_OPEN_VOICE=SPManage.getInstance().getBoolen("IS_OPEN_VOICE");
        Constant.TIME_SCREEN_JUMP=SPManage.getInstance().getInt("TIME_SCREEN_JUMP",100);
        Constant.CARD_LENGTH=SPManage.getInstance().getInt("CARD_LENGTH",8);
        til_account= (TextInputLayout) findViewById(R.id.til_account);
        et_accountNum= (TextInputEditText) findViewById(R.id.et_accountNum);
        til_pwd= (TextInputLayout) findViewById(R.id.til_pwd);
        et_password= (TextInputEditText) findViewById(R.id.et_password);
        btn_login= (Button) findViewById(R.id.btn_login);
        btn_urgentLogin= (Button) findViewById(R.id.btn_urgentLogin);
        tv_appSersion= (TextView) findViewById(R.id.tv_appSersion);

        tv_appSersion.setText("版本号："+ AppInfoUtil.getVersionName());

//        btn_urgentLogin.setVisibility(View.GONE);

        et_accountNum.setText(SPManage.getInstance().getString("loginaccoun"));
        et_password.setText(SPManage.getInstance().getString("loginpwd"));

        btn_login.setOnClickListener(this);
        btn_urgentLogin.setOnClickListener(this);
        et_accountNum.setOnFocusChangeListener(this);
        et_password.setOnFocusChangeListener(this);
    }
    private void initSDK() {
        SunmiSdkManage.getInstance()
                .sunmiInit(getApplicationContext(), mConnCallback);
    }

    private TextWatcher tWatcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    @Override
    public void onClick(View view) {
        hideKeyboard();
        switch (view.getId()){
            case R.id.btn_login:
                //登录
                login();
                break;
            case R.id.btn_urgentLogin:
                //紧急模式
                urgentLogin();
                break;
        }
    }

    /**紧急状态登录*/
    private void urgentLogin(){
//        String token =SPManage.getInstance().getToken();
//        if(TextUtils.isEmpty(token)){
//            Mtoast("用户token为空不能紧急登录");
//            return;
//        }
//        if(TextUtils.isEmpty(SPManage.getInstance().getString("serverUrl"))){
//            Mtoast("登录失败");
//            return;
//        }
            Constant.URGENT_TYPE=true;
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            finish();

    }
    /**开启获取取餐信息的服务*/
    private void startAllService() {
        Intent intent = new Intent(this, GetMakemealService.class);
        startService(intent);
//        Intent intent2 = new Intent(this, AdImageService.class);
//        startService(intent2);
    }

    /**判断是否要获得url*/
    private void isgetUrl(){
        if(!SPManage.getInstance().getBoolen("isdeletesp")){
            SPManage.getInstance().removesp();
            SPManage.getInstance().putBCommit("isdeletesp",Constant.IS_DELETE_SP);
//            Constant.IS_DELETE_SP=false;
        }
        serverUrl =SPManage.getInstance().getString("serverUrl");
        if(TextUtils.isEmpty(serverUrl)){
            getUrl();
        }else{
            HttpApiUrl.serverUrl=serverUrl;
            //获取取餐信息
            startAllService();
        }
    }

    /**获取后面请求的URL地址*/
    private void getUrl(){
        if( errorNum>=3){
            Mtoast("获取本机信息失败，请关闭APP重新进入！");
            return;
        }
        //获得SN
        String serialNum = android.os.Build.SERIAL;
//        Log.e(TAG, "serialNum=="+serialNum);
        Call<BaseBean<UrlBean>> call=HttpManage.getRequestUrlApi().getByMachine(serialNum);
        call.enqueue(new MyCallback<BaseBean<UrlBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<UrlBean>> call,
                                  Response<BaseBean<UrlBean>> response) {
                BaseBean<UrlBean> bean=response.body();
                    serverUrl=bean.getData().getApi();
                Gson gson=new Gson();
                String urlbean=gson.toJson(bean.getData());
                SPManage.getInstance().putCommit("urlbean",urlbean);
                SPManage.getInstance().putCommit("screenSize",bean.getData().getSize());
               if(bean.getData().getCard()==0){
                   SPManage.getInstance().putICommit("CARD_LENGTH",8);
                   Constant.CARD_LENGTH=bean.getData().getCard();
               }else{
                   SPManage.getInstance().putICommit("CARD_LENGTH",bean.getData().getCard());
                   Constant.CARD_LENGTH=bean.getData().getCard();
               }
//                Log.e("lh","getCard=="+bean.getData().getCard());
//                Log.e("lh","CARD_LENGTH=="+Constant.CARD_LENGTH);
//                Log.e("lh","sp=="+SPManage.getInstance().getInt("CARD_LENGTH",8));
                if(!TextUtils.isEmpty(serverUrl)){
                     HttpApiUrl.serverUrl=serverUrl;
                     bean.getData().getApp_function();
                     SPManage.getInstance().putCommit("serverUrl",serverUrl);
                    }
            }

            @Override
            public void onError(int code, String error) {
                errorNum++;
                getUrl();
            }
        });

    }

     /**登录方法*/
    private void login() {
        String accoun=til_account.getEditText().getText().toString().trim();
        if(TextUtils.isEmpty(accoun)){
            til_account.setError(getResources().getString(R.string.hint_accountNum));
            return;
        }
        String password=til_pwd.getEditText().getText().toString().trim();
        if(TextUtils.isEmpty(password)){
            til_pwd.setError(getResources().getString(R.string.hint_password));
            return;
        }
        Log.e(TAG,"login-HttpApiUrl=="+HttpApiUrl.serverUrl);
        if(TextUtils.isEmpty(serverUrl)){
            Mtoast("获取本机信息失败，请关闭APP重新进入！");
//            Mtoast("登录失败");
//            getUrl();
//            errorNum=0;
            return;
        }
        MyShowDialog.showLoadingDialog(LoginActivity.this,"登录中....");
        logincallback(accoun,password);
    }


       /**登录返回*/
    private void logincallback(final String accoun , final String password){

        Call<String> call1=HttpManage.getRequestApi().
                login(accoun,password,USER_LOGIN_TYPE);
        call1.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response,String data) {
                MyShowDialog.closeLoadingDialog();
                Gson gson=new Gson();
                LoginBean login=gson.fromJson(data,
                        LoginBean.class);
                SPManage.getInstance().putCommit("loginaccoun",accoun);
                SPManage.getInstance().putCommit("loginpwd",password);
                SPManage.getInstance().putCommit("token",login.getToken());

//                Gson gson=new Gson();
                String roles=gson.toJson(login.getRoles());
                SPManage.getInstance().putCommit("roles",roles);

                Intent intent=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                MyShowDialog.closeLoadingDialog();
                Mtoast(error);
            }
        });
    }

    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onFocusChange(View view, boolean b) {

        switch (view.getId()){
            case R.id.et_accountNum:
                if(b){
                    til_account.setErrorEnabled(false);
                }

                break;
            case R.id.et_password:
                if(b){
                    til_pwd.setErrorEnabled(false);
                }else{
                    if(et_accountNum.getText().toString().trim().length()==0){
                        til_account.setErrorEnabled(true);
                    }
                }
                break;
        }
    }

    private IConnectionCallback mConnCallback=new IConnectionCallback() {
        @Override
        public void onDisConnect() {

        }

        @Override
        public void onConnected(final ConnState state) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    Mtoast("state:"+state);
                    switch (state){
                        case AIDL_CONN:
                            //与本地service的连接畅通
                            break;
                        case VICE_SERVICE_CONN:
                            //与副屏service连接畅通
                            long fileId = SharedPreferencesUtil.getLong(getApplicationContext(),
                                    WELCOME_IMG_ID);
                            //判断文件是否存在
                            if(fileId!=-1L)SunmiSdkManage.getInstance()
                                    .checkImg(getApplicationContext(),
                                            fileId, WELCOME_IMG_ID);
                            SunmiSdkManage.getInstance().showWelcomImg();
                            break;
                        case VICE_APP_CONN:
                            //与副屏app连接畅通
                            break;
                    }
                }
            });
        }
    };
}
